<?php
namespace App\Api;

use App\Model\APP;
use App\Model\ELEVENACTIVITY;
use App\Model\ELEVENRECORD;
use App\Model\ELEVENUSER;
use App\Model\VERSION;
use App\Model\WALLETIOC;
use App\Model\WALLETTRADE;
use App\Model\WALLETWITHDRAW;
use PhalApi\Api;
use PhalApi\Exception;
use PhalApi\Exception\BadRequestException;
use PhalApi\Exception\InternalServerErrorException;
use App\Model\USER;
use App\Model\WALLETADDRESS;
use App\Common\WalletBase;
use App\Common\QRcode;


/**
 * 双十一活动
 *
 * @author: dogstar <chanzonghuang@gmail.com> 2014-10-04
 */

class Eleven extends BaseController
{
    private $starttime = '20181107';
    private $endtime = '20181120';
    CONST OFFICIALADDRESS = '0xc875d24eeb806df5320d08294a8fc3d5facd4a4f';          //官方钱包地址
    CONST OFFICIALUSERID = '100014';                         //官方钱包uid
    CONST USERID = '22020';                              //系统uid

    public function __construct()
    {
        header('Access-Control-Allow-Origin:*');
        // 响应类型
        header('Access-Control-Allow-Methods:POST');
        // 响应头设置
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        parent::__construct();
        if(time() < strtotime($this->starttime) || time() > strtotime($this->endtime))
        {
            // echo json_encode(['ret' => 400, 'data' => '', 'msg' => '活动还未开始']);
            // die;
        }
    }

    public function getRules()
    {
        return
            [
                '*' => [
                    'token' => ['name' => 'token', 'require' => true],
                    'api_version' => ['name' => 'api_version', 'require' => false],
                    'app_version' => ['name' => 'app_version', 'require' => false],
                ],
                'appInfo' => [
                    'activity_id' => ['name' => 'activity_id', 'require' => true],
                ],
                'poster' => [
                    'uid' => ['name' => 'uid', 'require' => true],
                    'd' => ['name' => 'd', 'require' => false],
                ],
                'inviter' => [
                    'p' => ['name' => 'p', 'require' => false],
                    'uid' => ['name' => 'uid', 'require' => true],
                ],
                'unchain' => [
                    'multiple' => ['name' => 'multiple', 'require' => true],
                    'activity_id' => ['name' => 'activity_id', 'require' => true],
                ],
                'rob' => [
                    'activity_id' => ['name' => 'activity_id', 'require' => true],
                    'multiple' => ['name' => 'multiple', 'require' => true],
                ],
                'telPhone' => [
                    'phone' => ['name' => 'phone', 'require' => true],
                    'uid' => ['name' => 'uid', 'require' => true],
                    'activity_id' => ['name' => 'activity_id', 'require' => false],
                ],
            ];
    }

    /**
     * 已邀请人列表
     */
    public function inviter()
    {
        if(!is_numeric($this->uid))
        {
            $uid = $this->decrypt(base64_decode($this->uid));
        }
        else
        {
            $uid = $this->uid;
        }
        $user = new USER();
        $user = $user->getUserById($uid);
        if(!$user)
        {
            throw new BadRequestException('用户不存在!');
        }
        $p = $this->p ? $this->p : 1;
        $user_ele = new ELEVENUSER();
        $user_info_img = $user_ele->getUserForDetail($uid);
        $inviter_num = count($user_info_img);
        $title = $this->title($inviter_num);

        $user_ele = $user_ele->getlist($uid, $p);
        $return = [];
        $return['multiple'] = $title['multiple'];
        $return['title'] = $title['title'];
        $return['remain_people'] = $title['remain_people'];
        $return['remain_multiple'] = $title['remain_multiple'];
        if($user_ele)
        {
            foreach($user_ele as $k => $v)
            {
                $return['list'][$k]['phone'] = substr($v['telphone'],0,4) . '***' . substr($v['telphone'], 8,3);
                $return['list'][$k]['time'] = date('Y-m-d H:i:s', $v['create_time']);
            }
        }
        else
        {
            $return['list'] = [];
        }

        return $return;
    }

    /**
     * 首页
     */
    public function index()
    {
        $activity = new ELEVENACTIVITY();
        $activity_list = $activity->getIco();
        $ico = '';
        foreach($activity_list as $v)
        {
            $ico .= $v['ico'].',';
        }
        $ico = trim($ico, ',');

        $user_model = new USER();
        $model = new WALLETADDRESS();
        $wallet = $model->getWalletByToken($this->token);
        if(!$wallet)
        {
            $return['code'] = "401";
        }
        $user = $user_model->getUserByToken($this->token);
        $user_ele = new ELEVENUSER();
        $eleven_user_info = $user_ele->checkGift($user['id']);
        $insert = [];
        if(!$eleven_user_info)
        {
            $insert['uid'] = $user['id'];
            $insert['inviterid'] = "0";
            if($user['login_time'] >= strtotime($this->starttime))
            {
                $insert['new_gift'] = 0;
            }
            else
            {
                $insert['new_gift'] = 1;
            }
            $insert['telphone'] = (int)$user['telphone'];
            $insert['create_time'] = time();
            $user_ele->insert($insert);
        }
        $user_info_img = $user_ele->getUserByInviter($user['id']);

        $ids = '';
        foreach($user_info_img as $v)
        {
            $ids .= $v['uid'] . ',';
        }
        $ids = trim($ids, ',');
        $user_info_img = [];
        if($ids)
        {
            $user_info_img = $user_model->getUserByIdLogin($ids, $this->starttime);
        }
        $inviter_num = count($user_info_img);
        $title = $this->title($inviter_num);
        $userimg = [];

        foreach($user_info_img as $v)
        {
            $userimg[] = 'http://www.byb.world' . $v['u_pic'];
        }
        $record = new ELEVENRECORD();
        $activity_list = $activity->getList($title['level']);
        $user_info = $user_ele->findByUid($user['id']);

        if($user_info && $user_info['new_gift'] == 0)
        {
            $new = $activity->getNew();
            $activity_list = array_merge($new, $activity_list);
        }
        foreach($activity_list as &$v)
        {
            $record_info = $record->findByIco($user['id'], $v['id']);
            $status = !empty($record_info) ? $record_info['status'] : 0;
            if($v['num'] < $v['send'] + $title['multiple'] * $v['multiple'])
            {
                $v['sort'] = 8;
                $v['status'] = '5';
            }
            if(time() > $v['end_time'])
            {
                $v['sort'] = 7;
                $v['status'] = '4';
            }
            if(time() < $v['start_time'])
            {
                if(empty($first))
                {
                    $first = 'exist';
                    $v['sort'] = -1;
                }
                else
                {
                    $v['sort'] = 3;
                }
                $v['status'] = '3';
            }
            $v['icon'] = HOST . $v['ico_icon'];
            if(!empty($v['status']) && $status == 0)
            {
                $v['status'] = strval($v['status']);
            }
            else
            {
                if($status == 0)
                {
                    $v['sort'] = 1;
                }
                elseif($status == 1)
                {
                    $v['sort'] = 2;
                }
                elseif($status == 2)
                {
                    $v['sort'] = 6;
                }
                else
                {
                    $v['sort'] = $status;
                }
                $v['status'] = strval($status);
            }
            $v['already'] = strval(round(($v['send'] / $v['num'])*100, 0));
            if($v['level'] == 0)
            {
                $v['sort'] = -2;
                $v['multiple'] = "1";
            }
            else
            {
                $v['multiple'] = $title['multiple'];
            }
        }
        // 排序
        array_multisort(array_column($activity_list,'sort'),array_column($activity_list,'start_time'),SORT_ASC,$activity_list);
        $return['ico'] = $ico;
        $return['invite'] = 'http://www.byb.world/eleven/invite.html?uid=' . $user['id'];
        $return['rule'] = 'http://byb.world/index.php/NewsInfo/bkInfo/id/218300/uid/222811/tj_uid/222811';
        $return['strategy'] = 'http://www.byb.world/index.php/NewsInfo/bkInfo/id/218068';
        $return['people'] = \PhalApi\DI()->redis->get_forever('num', 0);
        $return['title'] = '“' . $title['title'] . '”';
        $return['multiple'] = $title['multiple'];
        $return['userimg'] = array_slice($userimg, 0, 8);
        $return['icolist'] = $activity_list;

        return $return;
    }

    /**
     *  首页抢币
     */

    public function label()
    {
        $user = new USER();
        $user = $user->getUserByToken($this->token);
        $user_ele = new ELEVENUSER();
        $user_info_img = $user_ele->getUserForDetail($user['id']);
        $inviter_num = count($user_info_img);
        $title = $this->title($inviter_num);
        $userimg = [];
        foreach($user_info_img as $v)
        {
            $userimg[] = $v['u_pic'];
        }
        $record = new ELEVENRECORD();
        $activity = new ELEVENACTIVITY();
        $activity_list = $activity->getList($title['level']);
        $user_info = $user_ele->findByUid($user['id']);
        if($user_info && $user_info['new_gift'] == 0)
        {
            $new = $activity->getNew();
            $activity_list = array_merge($new, $activity_list);
        }
        foreach($activity_list as &$v)
        {
            $record_info = $record->findByIco($user['id'], $v['id']);
            $status = !empty($record_info) ? $record_info['status'] : 0;
            if($v['num'] < $v['send'] + $title['multiple'] * $v['multiple'])
            {
                $v['sort'] = 5;
                $v['status'] = '5';
            }
            if(time() > $v['end_time'])
            {
                $v['sort'] = 4;
                $v['status'] = '4';
            }
            if(time() < $v['start_time'])
            {
                if(empty($first))
                {
                    $first = 'exist';
                    $v['sort'] = -1;
                }
                else
                {
                    $v['sort'] = 6;
                }

                $v['status'] = '3';
            }
            $v['icon'] = HOST . $v['ico_icon'];
            if(!empty($v['status']) && $status == 0)
            {
                $v['status'] = strval($v['status']);
            }
            else
            {
                $v['sort'] = $status;
                $v['status'] = strval($status);
            }
            $v['already'] = strval(round(($v['send'] / $v['num'])*100, 0));
            if($v['level'] == 0)
            {
                $v['sort'] = -2;
                $v['multiple'] = "1";
            }
            else
            {
                $v['multiple'] = $title['multiple'];
            }
        }
        array_multisort(array_column($activity_list,'sort'),array_column($activity_list,'start_time'),SORT_ASC,$activity_list);
        return $activity_list;
    }

    /**
     *  我的战果
     */
    public function prizeList()
    {
        $user = new USER();
        $user = $user->getUserByToken($this->token);
        $record = new ELEVENRECORD();
        $record_activity = $record->getActivity($user['id']);
        $activity_id = '';
        foreach($record_activity as $v)
        {
            $activity_id .= $v['activity_id'] . ',';
        }
        $activity_id = trim($activity_id,',');
        if(!$activity_id)
        {
            $activity_list = [];
        }
        else
        {
            $activity = new ELEVENACTIVITY();
            $activity_list = $activity->getByIds('(' . $activity_id . ')');
        }
        foreach($activity_list as &$v)
        {
            $record_info = $record->findByIco($user['id'], $v['id']);
            $v['status'] = !empty($record_info) ? $record_info['status'] : 0;
            $v['sort'] = $v['status'];
            $v['status'] = strval($v['status']);
            $v['already'] = strval(round(($v['send'] / $v['num'])*100, 0));
            $v['icon'] = HOST . $v['ico_icon'];
            $v['sort'] = $v['status'];
        }
        array_multisort(array_column($activity_list,'sort'),SORT_ASC,$activity_list);

        return $activity_list;
    }
//解锁
    public function unchain()
    {
        $user = new USER();
        $user_info = $user->getUserByToken($this->token);
        $record = new ELEVENRECORD();
        $record_info = $record->findByIco($user_info['id'], $this->activity_id);

        if(!$record_info || $record_info['status'] != '1')
        {
            throw new BadRequestException('异常!');
        }
        if($record_info['status'] == 2)
        {
            throw new BadRequestException('已解锁!');
        }
        $activity = new ELEVENACTIVITY();
        $activity_info = $activity->getById($this->activity_id);
        if(!$activity_info)
        {
            throw new BadRequestException('没有这个活动!');
        }
        if($activity_info['level'] == 0)
        {
            $this->multiple = 1;
        }

        try
        {
            $this->Wheel($activity_info['ico'], $this->multiple * $activity_info['unit']);
            $data['num'] = $this->multiple;
            $data['status'] = 2;
            $data['update_time'] = time();
            $record->update($record_info['id'], $data);
        }
        catch (Exception $e)
        {
            \PhalApi\DI()->logger->error('{双十一活动},用户id:'.$user_info['id'].',交易失败:'.$e->getMessage());
            throw new BadRequestException('解锁失败,请过半小时重试!');
            //throw new BadRequestException('转账失败!'. $e->getMessage());
        }
        return 'ok';
    }

    /**
     * 抢币
     * @param
     * @return
     */
    public function rob()
    {
        $activity = new ELEVENACTIVITY();
        $activity_info = $activity->getById($this->activity_id);
        if($activity_info['level'] == 0)
        {
            $this->multiple = 1;
        }
        if($activity_info['start_time'] > time())
        {
            throw new BadRequestException('活动还未开始!');
        }
        if($activity_info['end_time'] < time())
        {
            throw new BadRequestException('活动已结束!');
        }
        if($activity_info['send'] + $this->multiple * $activity_info['multiple'] > $activity_info['num'])
        {
            throw new BadRequestException('该币已领取完!');
        }
        $user = new USER();
        $user_info = $user->getUserByToken($this->token);
        if(!$user_info)
        {
            throw new BadRequestException('该用户不存在!');
        }

        if(\PhalApi\DI()->redis->get_forever('trade:' . $user_info['id'] . '-' . $this->activity_id, 0))
        {
            throw new BadRequestException('您已领取过该活动!');
        }

        $eleven_user = new ELEVENUSER();
        $eleven_user_info = $eleven_user->checkGift($user_info['id']);
        if(!$eleven_user_info)
        {
            throw new BadRequestException('请登录抢币首页!');
        }

        if($activity_info['level'] == 0)
        {
            // 已领取过新手礼包
            if($eleven_user_info && $eleven_user_info['new_gift'] == 1)
            {
                throw new BadRequestException('您已领取新用户礼包!');
            }
            //还未领取新手礼包
            elseif($eleven_user_info['new_gift'] == 0)
            {
                $data['new_gift'] = 1;
                $data['update_time'] = time();
                $eleven_user->update($eleven_user_info['id'], $data);
            }
        }

        $update['real_send'] = $activity_info['real_send'] + $this->multiple;
        $update['send'] = $activity_info['send'] + $this->multiple * $activity_info['multiple'];
        $activity->update($activity_info['id'], $update);
        $record = new ELEVENRECORD();
        $insert = [];
        $insert['uid'] = $user_info['id'];
        $insert['activity_id'] = $this->activity_id;
        $insert['num'] = $this->multiple;
        $insert['create_time'] = time();
        $insert['status'] = 1;
        $record->insert($insert);
        \PhalApi\DI()->redis->set_forever('trade:' . $user_info['id'] . '-' . $this->activity_id,'1',0);
        return ['num' => strval($this->multiple * $activity_info['unit']), 'ico' => strval($activity_info['ico'])];
    }

    /**
     * @return app详情
     */
    public function appInfo()
    {
        $activity = new ELEVENACTIVITY();
        $activity_info = $activity->getById($this->activity_id);
        $app = new APP();
        $app = $app->getApps($activity_info['app_id']);
        $app['slogan'] = $activity_info['slogan'];
        $app['content'] = strip_tags(str_replace('&nbsp;', '', htmlspecialchars_decode($activity_info['content'])));
        return $app;
    }

    public function invite()
    {
        $activity = new ELEVENACTIVITY();
        $activity = $activity->getNew();
        if(!$activity)
        {
            throw new BadRequestException('新手礼包呢?');
        }
        $data['ico'] = $activity[0]['ico'];
        $data['icon'] = HOST . $activity[0]['ico_icon'];
        $data['price'] = trim(trim(sprintf("%.3f",$activity[0]['price']), '0'),'.');
        $data['unit'] = sprintf("%.3f",$activity[0]['unit']);
        $data['send'] = $activity[0]['send'];
        $data['num'] = $activity[0]['num'];
        $data['multiple'] = round(($activity[0]['send'] / $activity[0]['num']) * 100, 2);
        return $data;
    }

    public function telPhone()
    {

        if(!preg_match("/^1[345789]{1}\d{9}$/",$this->phone))
        {
            throw new BadRequestException('手机号格式不正确!', '1');
        }
        $user = new USER();
        $check = $user->getUserByPhone($this->phone);
        if($check)
        {
            throw new BadRequestException('该手机号已是币用宝用户!', '2');
        }
        $eleven_user = new ELEVENUSER();
        $check_eleven = $eleven_user->getByPhone($this->phone);
        if($check_eleven)
        {
            throw new BadRequestException('该手机号已参与,请注册并登录激活!', '3');
        }

        if(!is_numeric($this->uid))
        {
            $uid = $this->decrypt(base64_decode($this->uid));
        }
        else
        {
            $uid = $this->uid;
        }

        $user_info = $user->getUserById($uid);
        if(!$user_info)
        {
            throw new BadRequestException('该用户不存在!', '4');
        }
        $insert['inviterid'] = $user_info['id'];
        $insert['telphone'] = $this->phone;
        $insert['create_time'] = time();
        if($eleven_user->insert($insert))
            return '注册成功';
        throw new BadRequestException('系统异常!');
    }

    /**
     * 邀请海报 h5
     * @return array
     * @throws BadRequestException
     */

    public function poster()
    {
        if(!is_numeric($this->uid))
        {
            $uid = $this->decrypt(base64_decode($this->uid));
        }
        else
        {
            $uid = $this->uid;
        }

        if($this->d)
        {
            shell_exec('rm '.$this->d);
        }
        $user = new USER();
        $user_info = $user->getUserById($uid);
        $user_ele = new ELEVENUSER();
        $user_ele_info = $user_ele->checkGift($uid);
        if(!$user_ele_info)
        {
            $filename = 'invite/'. $this->uid .'.png';
            QRcode::png('http://www.byb.world/eleven/share.html?uid='.$this->uid,$filename , 'L', 6, 2);
            $insert['uid'] = $uid;
            $insert['inviterid'] = "0";
            if($user_info['login_time'] >= strtotime($this->starttime))
            {
                $insert['new_gift'] = 0;
            }
            else
            {
                $insert['new_gift'] = 1;
            }
            $insert['qrcode'] = '/'. $filename;
            $insert['telphone'] = (int)$user_info['telphone'];
            $insert['create_time'] = time();
            $user_ele->insert($insert);
            $qrcode = HOST . $insert['qrcode'];
        }
        elseif(!$user_ele_info['qrcode'])
        {
            $filename = 'invite/'. $this->uid .'.png';
            QRcode::png('http://www.byb.world/eleven/share.html?uid='.$this->uid,$filename , 'L', 6, 2);
            $update['qrcode'] = '/'. $filename;
            $user_ele->update($user_ele_info['id'], $update);
            $qrcode = HOST . $update['qrcode'];
        }
        else
        {
            $qrcode = HOST . $user_ele_info['qrcode'];
        }
        return ['qrcode' => $qrcode , 'count' => \PhalApi\DI()->redis->get_forever('num', 0)];
    }

    public function title($inviter_num)
    {
        if($inviter_num < 3)
        {
            $multiple = '1';
            $title = '币迷';
            $level = '1';
            $remain_people = strval(3 - $inviter_num);
            $remain_multiple = '3';
        }
        elseif($inviter_num < 5)
        {
            $multiple = '3';
            $title = '币痴';
            $level = '2';
            $remain_people = strval(5 - $inviter_num);
            $remain_multiple = 4;
        }
        elseif($inviter_num < 10)
        {
            $multiple = '4';
            $title = '币侠';
            $level = '3';
            $remain_people = strval(10 - $inviter_num);
            $remain_multiple = '6';
        }
        elseif($inviter_num < 20)
        {
            $multiple = '6';
            $title = '币霸';
            $level = '4';
            $remain_people = strval(20 - $inviter_num);
            $remain_multiple = '10';
        }
        elseif($inviter_num < 30)
        {
            $multiple = '10';
            $title = '币神';
            $level = '5';
            $remain_people = strval(30 - $inviter_num);
            $remain_multiple = '15';
        }
        elseif($inviter_num >= 30)
        {
            $multiple = '15';
            $title = '币圣';
            $level = '6';
            $remain_people = '0';
            $remain_multiple = '0';
        }
        return ['title' => $title, 'multiple' => $multiple, 'level' => $level, 'remain_people' => $remain_people, 'remain_multiple' => $remain_multiple];
    }

    /**
     * 双十一活动转币
     * @return array
     * @throws BadRequestException
     */
    public function Wheel($ico_name, $num)
    {
        $model = new WALLETADDRESS();
        $ico = new WALLETIOC();
        $data = $model->getWalletByToken($this->token);
        $ico = $ico->getIoc($ico_name);
        if(!$ico)
            throw new BadRequestException('这个币不存在');

        /**
         * 获取余额
         */

        $accounts = WalletBase::accounts(self::OFFICIALUSERID);
        $balance = $eth = 0;
        foreach($accounts->spotAccounts as $k => $v)
        {
            if($v->currency == $ico_name && $v->type == 'SPOT_AVAILABLE')
            {
                $balance = $v->balance;
            }
        }

        if($balance < $num)
        {
            throw new BadRequestException('余额不足');
        }

        $account = WalletBase::accounts($data['wallet_userid']);
        $tobalance = 0;
        foreach($account->spotAccounts as $k => $v)
        {
            if($v->currency == $ico_name && $v->type == 'SPOT_AVAILABLE')
            {
                $tobalance = $v->balance;
            }
        }

        $transfer = WalletBase::transfer($num, $ico_name, self::OFFICIALUSERID, $data['wallet_userid']);

        if(!empty($transfer->from->id))
        {
            \PhalApi\DI()->logger->info('{双十一活动},用户id:'.$data['uid'].',交易成功;数量:'.$num.',币种:'.$ico_name);
            $trade = new WALLETTRADE();
            $insert = [];
            $insert['type'] = 5;            //双十一活动
            $insert['balance'] = $balance - $num;
            $insert['tobalance'] = $tobalance + $num;
            $insert['num'] = $num;
            $insert['fromuid'] = self::USERID;
            $insert['touid'] = $data['uid'];
            $insert['ico'] = $ico_name;
            $insert['fromaddress'] = self::OFFICIALADDRESS;
            $insert['toaddress'] = $data['wallet_address'];
            $insert['style'] = 1;               //内部转账
            $insert['create_time'] = time();
            $trade->insert($insert);
            return [true, 'msg' => '交易成功'];
        }
        \PhalApi\DI()->logger->error('{双十一活动},用户id:'.$data['uid'].',交易失败:'.$transfer->message);
        throw new BadRequestException($transfer->message);
    }

    public function refrush()
    {
        \PhalApi\DI()->redis->flushDB(0);
        \PhalApi\DI()->redis->set_forever('num' , '46836' , 0);
    }
}